<template>
  <div class="box">
    <el-card shadow class="card">
      <!-- 1.面包屑 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ name: 'backstage' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>学员管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 2.搜索 -->
      <el-input
        placeholder="请输入学员姓名"
        v-model="search"
        class="with-input"
        clearable>
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="searchUser"
        ></el-button>
      </el-input>
      <!-- 添加学员按钮 -->
      <el-button type="success" plain @click="dialogVisible">添加学员</el-button>
      <!-- 3.表格 -->
      <el-table :data="userData" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column
          prop="address"
          label="住址"
          width="280"
        ></el-table-column>
        <el-table-column prop="model" label="申请车型"></el-table-column>
        <el-table-column prop="coach" label="教练"></el-table-column>
        <el-table-column prop="date" label="领证日期"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              plain
              @click="hendleEdit(scope.$index, scope.row)"
            ></el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该用户信息吗？"
              @confirm="handleDelete(scope.$index, scope.row)">
              <el-button
                slot="reference"
                type="danger"
                plain
                circle
                icon="el-icon-delete">
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 4.分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="length">
      </el-pagination>
    </el-card>
    <!-- 添加学员的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogStudentFormVisible"
      width="440px">
      <el-form :model="studentForm" :rules="studentRules" ref="formStudent">
        <el-form-item prop="name">
          <el-input v-model="studentForm.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="studentForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="address">
          <el-input v-model="studentForm.address" placeholder="住址"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model.number="studentForm.phone"
            placeholder="电话"
          ></el-input>
        </el-form-item>
        <el-form-item prop="model">
          <el-select
            v-model="studentForm.model"
            placeholder="申请车型"
            style="width: 100%">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :prop="!datedisable ? 'date' : ''">
          <el-date-picker
            v-model.lazy="studentForm.date"
            placeholder="选择领证日期"
            style="width: 100%"
            :disabled="datedisable">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="coach">
          <el-select
            v-model="studentForm.coach"
            placeholder="请选择教练"
            style="width: 100%">
            <el-option
              v-for="item in coachName"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStudentFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUser">保存信息</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserData,
  addUserData,
  updateUserData,
  deleteUserData,
} from "@/api/data";
export default {
  name: "StudentUser",
  data() {
    return {
      search: "", // 搜索输入框输入的内容
      page: 1, // 当前页数
      limit: 2, // 每条页面条数
      length: 0, // 获取数据的长度
      isAdd: true, // false: 编辑 true: 添加
      datedisable: true, // 只有当管理员编辑学员信息时，date-picker生效
      dialogStudentFormVisible: false, // 控制学员对话框的显示与隐藏
      userData: [], // 请求获取的学员或教练数据
      coachName: new Set(), // 获取教练名集合
      // 学员表单
      studentForm: {
        name: "",
        sex: "男",
        address: "",
        phone: "",
        model: "",
        date: "",
        coach: "",
      },
      // 学员表单验证规则
      studentRules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 2, max: 6, message: "长度在2到6个字符", trigger: "blur" },
        ],
        address: [{ required: true, message: "住址不能为空", trigger: "blur" }],
        date: {
          type: "date",
          required: true,
          message: "请选择日期",
          trigger: "change",
        },
        phone: [{ validator: this.checkPhone, trigger: ["blur", "change"] }],
        model: [
          {
            required: true,
            message: "申请车型不能为空",
            trigger: ["blur", "change"],
          },
        ],
        coach: [
          {
            required: true,
            message: "教练名不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      // 驾驶证申请车型的选项
      options: [
        { label: "C1", value: "C1" },
        { label: "C2", value: "C2" },
        { label: "A1", value: "A1" },
        { label: "A2", value: "A2" },
      ],
      title: "",
    };
  },
  methods: {
    // 自定义电话的验证规则
    checkPhone(_, value, callback) {
      if (value === "") {
        callback(new Error("电话不能为空"));
      } else {
        let regphone = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (!regphone.test(value)) {
          callback(new Error("手机格式不正确"));
        } else {
          callback();
        }
      }
    },
    // 搜索功能实现
    async searchUser() {
      this.length = (
        await getUserData({ url: "/student", like: this.search })
      ).data.length;
      this.limit = 2;
      this.page = 1;
      this.getUserList();
    },
    // 获取学员数据
    async getUserList() {
      this.userData = (
        await getUserData({
          url: "/student",
          page: this.page,
          limit: this.limit,
          like: this.search,
        })
      ).data;
    },
    // 当每页条数发生变化使调用
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.getUserList();
    },
    // 当页数发生变化时调用
    handleCurrentChange(val) {
      this.page = val;
      this.getUserList();
    },
    // 显示添加学员的对话框
    dialogVisible() {
      // 清空表单
      this.studentForm = { sex: "男" };
      this.datedisable = true;
      // 显示添加学员对话框
      this.isAdd = true;
      this.title = "添加学员信息";
      this.dialogStudentFormVisible = true;
    },
    // 添加学员信息到json-server数据库
    addUser() {
      this.$refs["formStudent"].validate(async (valid) => {
        if (valid) {
          this.dialogStudentFormVisible = false;
          // 发送数据
          if ((await addUserData("/student", this.studentForm)).data) {
            // 重新获取学员/教练数据
            this.page = 1;
            this.search = "";
            this.getCoachName();
            this.getUserList();
            // 清空表单
            this.studentForm = { sex: "男" };
            // 提示信息
            this.$message.success("学员添加成功");
          }
        } else {
          this.$message.info("表单验证信息不通过");
        }
      });
    },
    // 根据id更新学员/教练信息到json-server数据库
    updateUser() {
      this.$refs["formStudent"].validate(async (valid) => {
        if (valid) {
          this.dialogStudentFormVisible = false;
          // 发送数据
          if (
            (
              await updateUserData(
                "/student",
                this.studentForm.id,
                this.studentForm
              )
            ).data
          ) {
            // 重新获取学员/教练数据
            this.page = 1;
            this.search = "";
            this.getCoachName();
            this.getUserList();
            // 清空表单
            this.studentForm = { sex: "男" };
            // 提示信息
            this.$message.success("学员修改成功");
          }
        } else {
          this.$message.info("表单验证信息不通过");
        }
      });
    },
    // 删除学员
    async handleDelete(_, row) {
      const { status } = await deleteUserData("/student", row.id);
      if (status >= 200 && status < 300) {
        // 重新获取学员/教练数据
        this.page = 1;
        this.search = "";
        this.getCoachName();
        this.getUserList();
        // 提示信息
        this.$message.success("学员删除成功");
      }
    },
    // 获取教练名
    async getCoachName() {
      (await getUserData({ url: "/coach" })).data.forEach((element) => {
        this.coachName.add(element.name);
      });
    },
    handleUser() {
      // 确定是添加还是编辑操作
      if (this.isAdd) {
        this.addUser();
      } else {
        this.updateUser();
      }
    },
    // 编辑学员或教练信息
    hendleEdit(_, row) {
      this.isAdd = false;
      this.title = "编辑学员信息";
      this.studentForm = row;
      this.dialogStudentFormVisible = true;
      // date-picker的使能
      this.datedisable = false;
    },
  },
  async mounted() {
    // 获取学员和教练信息长度
    this.length = (await getUserData({ url: "/student" })).data.length;
    // 获取json-server数据库中教练姓名
    // 注意在添加学员/教练时，需要重新获取一遍数据
    this.getCoachName();
    // 获取学员数据
    this.getUserList();
  },
};
</script>

<style scoped>
.box,
.card {
  height: 100%;
}
.with-input {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-right: 10px;
}
.pagination {
  margin-top: 30px;
}
.changeButton {
  margin-bottom: 30px;
  margin-left: 10px;
}
</style>